﻿using System;
using Microsoft.DirectX;

//http://nehe.gamedev.net/tutorial/collision_detection/17005/

namespace WolfGame {
  class p_Collisions {

    #region Member Variables

    private Common common;
    private Vector3 point1, point2, point3, point4; //points to check against

    #endregion

    #region Constructor

    /// <summary>
    /// Instantiate the class
    /// </summary>
    /// <param name="common"></param>
    public p_Collisions(Common common) {
      this.common = common;
    }

    #endregion

    #region Detection

    /// <summary>
    /// Figure out if the entity can result in the direction it wants to
    /// </summary>
    /// <param name="position"></param>
    /// <param name="futurePos"></param>
    /// <param name="radius"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    public Vector3 CalculateMovement(Vector3 position, Vector3 futurePos, float radius, float height) {
      //Vector3 result = new Vector3(0f, -common.Gravity, 0f);
      Vector3 result = new Vector3(1f, 0f, 1f);

      //Check 4 points
      /*                 /                    +Y
       *       Point 1  /                 +X  /
       *             | /                  /\ / 
       * Point 4 ---------- Point 2       | /
       *            /|                    |/
       *           / Point 3              -----> +Z
       *         */
      point1.X = futurePos.X + radius;
      point1.Y = futurePos.Y;
      point1.Z = futurePos.Z;

      point2.X = futurePos.X;
      point2.Y = futurePos.Y;
      point2.Z = futurePos.Z + radius;

      point3.X = futurePos.X - radius;
      point3.Y = futurePos.Y + height;
      point3.Z = futurePos.Z;

      point4.X = futurePos.X;
      point4.Y = futurePos.Y + height;
      point4.Z = futurePos.Z - radius;

      for (int i = 0; i < common.Map.Planes.Count; i++) {
        // Check in the X direction
        if (point2.Z > common.Map.Planes[i].v3.X && point4.Z < common.Map.Planes[i].v3.Y && result.Z != 0) {
          if ((point1.X > common.Map.Planes[i].v1.X && point1.X < common.Map.Planes[i].v1.Y) ||
            (point3.X > common.Map.Planes[i].v1.X && point3.X < common.Map.Planes[i].v1.Y)) {

            result.Z = 0f;
            break;
          }
        }
        // Check in the Z direction
        if (point1.X > common.Map.Planes[i].v1.X && point3.X < common.Map.Planes[i].v1.Y && result.X != 0) {
          if ((point2.Z > common.Map.Planes[i].v3.X && point2.Z < common.Map.Planes[i].v3.Y) ||
            (point4.Z > common.Map.Planes[i].v3.X && point4.Z < common.Map.Planes[i].v3.Y)) {

            result.X = 0f;
            break;
          }
        }
      }

      return result;
    }

    #endregion
  }
}
